package com.wt.springsamples.controller;

import com.wt.springsamples.common.ApiResult;
import com.wt.springsamples.common.BizException;
import com.wt.springsamples.model.dto.UserLoginInfo;
import com.wt.springsamples.biz.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.stream.Collectors;

@Api("登录管理")
@Controller
@Slf4j
@RequestMapping("/api")
public class LoginController{

    @Autowired
    private ISysUserService sysUserService;

    @ApiOperation(value ="captcha:captcha",nickname = "获取验证码")
    @GetMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.info(this.getClass().getCanonicalName()+":captcha方法");
        CaptchaUtil.out(120, 45, 4, request, response);
    }

    @GetMapping("/getLoginInfo")
    @ResponseBody
    public ApiResult loginInfo(@AuthenticationPrincipal Authentication authentication) {
        authentication  = SecurityContextHolder.getContext().getAuthentication();
        if(authentication==null){
            throw new BizException(5001,"未完成登录验证！");
        }
        String scope = authentication.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .collect(Collectors.joining(" "));
//        SysUser sysUser = sysUserService.selectByLoginName(authentication.getName());

        UserLoginInfo userLoginInfo = sysUserService.getUserLoginInfoByLoginName(authentication.getName());
//        userService.getById();
//        Map userinfo = new HashMap();
//        userinfo.put("username",loginUser.getUsername());
//        userinfo.put("username",loginUser.getUsername());
//        userinfo.put("authorities",authentication.getAuthorities());
//        userinfo.put("scope",scope);

        return ApiResult.ok(userLoginInfo);
    }
}
